package com.kws.tool.config;

import cn.hutool.core.bean.BeanDesc;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kws.tool.entity.MerchantUserChat;
import com.kws.tool.service.MerchantUserChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: yxy
 * @Date: 2024-10-31
 */
@Component
@Slf4j
@ServerEndpoint("/websocket/pushMessage/{userId}")
public class WebSocketServer {
    /**
     * 静态变量，用来记录当前在线连接数
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);
    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象。
     */
    public static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收userId
     */
    private String userId = "";

    /**
     * 连接建立成
     * 功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //加入set中
            webSocketMap.put(userId, this);
        } else {
            //加入set中
            webSocketMap.put(userId, this);
            //在线数加1
            addOnlineCount();
        }

        log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg","连接成功");
        sendMessage(jsonObject.toJSONString());
	}

    /**
     * 连接关闭
     * 调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
    }

    public static Queue<String> queue = new LinkedList<>();
    /**
     * 收到客户端消
     * 息后调用的方法
     *
     * @param message 客户端发送过来的消息
     **/
    @OnMessage
    public void onMessage(String message, Session session) {
//        log.info("用户消息:" + userId + ",报文:" + message);
        log.info("消息:" + userId);
        //可以群发消息
        //消息保存到数据库、redis
        if (StringUtils.isNotEmpty(message)) {
        log.info("用户消息:" + userId);
            try {
//                message = message.replaceAll("\r\n", "");
                MerchantUserChat merchantUserChat = JSONObject.parseObject(message, MerchantUserChat.class);


                Long sendUser = merchantUserChat.getSendUser();
                Long toUser = merchantUserChat.getToUser();
                String roomId = merchantUserChat.getRoomId();
                if (sendUser == null) {
                    return;
                }
                //存入消息队列
                queue.offer(message);
                /*if (!StringUtils.isEmpty(roomId)){
                    //房间号不存在，则需要发送消息到用户，存在则存储到数据
                    sendInfo(message,String.valueOf(toUser));

                }
                merchantUserChat.setStatus(1);//默认未读
                merchantUserChat.setEnable("1");//默认可用
                merchantUserChatService.save(merchantUserChat);*/
            } catch (Exception e) {
				log.error("消息发送错误："+e.getMessage());
                e.printStackTrace();
            }
        }
    }


    // 定期处理消息队列中的消息
    @Scheduled(fixedDelay = 1000)
    public void processMessages() {
        while (!queue.isEmpty()) {

            String msg = queue.poll();
            MerchantUserChatService merchantUserChatService = SpringUtil.getBean(MerchantUserChatService.class);
            MerchantUserChat merchantUserChat = JSONObject.parseObject(msg, MerchantUserChat.class);
            System.out.println(merchantUserChat.getContent());
            merchantUserChat.setStatus(1);//默认未读
            merchantUserChat.setEnable("1");//默认可用
            merchantUserChatService.save(merchantUserChat);
        }
    }



    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {

        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }
    /**
     * 实现服务
     * 器主动推送
     */
    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message,true);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送自定
     * 义消息
     **/
    public static boolean sendInfo(String message, String userId) {
        log.info("发送消息到:" + userId + "，报文:" + message);
        if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
            return true;
        } else {
            log.error("用户" + userId + ",不在线！");
            return false;
        }
    }

    /**
     * 获得此时的
     * 在线人数
     *
     * @return
     */
    public static synchronized AtomicInteger getOnlineCount() {
        return onlineCount;
    }

    /**
     * 在线人
     * 数加1
     */
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount.getAndIncrement();
    }

    /**
     * 在线人
     * 数减1
     */
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount.getAndDecrement();
    }

}

